from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django_editorjs_fields import EditorJsJSONField
from user.models import User
import pghistory
from django.core.files.storage import default_storage
from django.conf import settings

def validate_editorjs_data(value):
    """验证 EditorJS 数据结构"""
    if not isinstance(value, dict):
        raise ValidationError('数据必须是字典格式')
    if 'blocks' not in value:
        raise ValidationError('缺少必需的 blocks 字段')
    if not isinstance(value['blocks'], list):
        raise ValidationError('blocks 必须是列表格式')

@pghistory.track(
    pghistory.InsertEvent(), pghistory.UpdateEvent(), pghistory.DeleteEvent()
)
class Post(models.Model):
    title = models.CharField("标题", max_length=200)
    content = EditorJsJSONField(
        verbose_name="正文",
        default=dict,
        validators=[validate_editorjs_data],
        plugins=[],
        tools={},
    )
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts", verbose_name="作者")
    created_at = models.DateTimeField("创建时间", auto_now_add=True)
    published_at = models.DateTimeField("发布时间", null=True, blank=True)
    last_modified_at = models.DateTimeField("最后修改时间", auto_now=True)
    view_times = models.PositiveIntegerField("浏览次数", default=0)
    private = models.BooleanField("不公开展示", default=False, help_text="发布后只有自己能看到")
    draft = models.BooleanField("草稿", default=True)
    likes = GenericRelation('Like', related_query_name='post')

    class Meta:
        verbose_name = "日志"
        verbose_name_plural = "日志"

    def __str__(self):
        return self.title

    def delete(self, *args, **kwargs):
        # 删除文章中的图片
        if self.content and 'blocks' in self.content:
            for block in self.content['blocks']:
                if block.get('type') == 'image' and 'file' in block.get('data', {}):
                    # 从 URL 中获取文路径并删除
                    file_path = block['data']['file']['url'].replace(settings.MEDIA_URL, '', 1)
                    if default_storage.exists(file_path):
                        default_storage.delete(file_path)
        super().delete(*args, **kwargs)

@pghistory.track(
    pghistory.InsertEvent(), pghistory.UpdateEvent(), pghistory.DeleteEvent()
)
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments", verbose_name="日志")
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments", verbose_name="评论者")
    content = models.TextField("评论内容")
    created_at = models.DateTimeField("创建时间", auto_now_add=True)
    is_displayed = models.BooleanField("是否显示", default=False)
    likes = GenericRelation('Like', related_query_name='comment')

    class Meta:
        verbose_name = "评论"
        verbose_name_plural = "评论"

    def __str__(self):
        return f"{self.author.username} 对 {self.post.title} 的评论"

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="likes", verbose_name="用户")
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, verbose_name="内容类型")
    object_id = models.PositiveIntegerField("对象ID")
    content_object = GenericForeignKey('content_type', 'object_id')
    created_at = models.DateTimeField("创建时间", auto_now_add=True)

    class Meta:
        verbose_name = "喜欢"
        verbose_name_plural = "喜欢"
        unique_together = ('user', 'content_type', 'object_id')

    def __str__(self):
        return f"{self.user.username} 喜欢 {self.content_object}"
